<template>
  <t-dialog :visible.sync="visible" header="编 辑" @confirm="handleConfirm" @cancel="handleCancel" @close="handleCancel">
    <t-form ref="formRef" :data="form" :rules="rules">
      <t-form-item label="名 称" name="name">
        <t-input v-model="form.name" placeholder="请输入名称" clearable />
      </t-form-item>
      <t-form-item label="上级部门" name="parentId">
        <t-cascader v-model="form.parentId" :options="options" clearable placeholder="请选择" />
      </t-form-item>
    </t-form>
  </t-dialog>
</template>
<script setup lang="ts">
import { ref, defineExpose } from 'vue';
import { MessagePlugin, FormRules, } from 'tdesign-vue-next';
import { update, getById } from '@/api/userCenter/dept/dept';
const visible = ref?.(false);
const loading = ref?.(false);
const formRef = ref?.(null);
const form = ref?.({
  id: '',
  parentId: '',
  name: '',
  content: ''
});
// 表单验证规则
const rules: FormRules = {
  name: [{ required: true, message: '请输入名称', type: 'error' }],
};
const options = ref?.([]);
const handleConfirm = async () => {
  if (!formRef) return;
  // 先进行表单验证
  const valid = await formRef?.value?.validate?.();
  if (valid !== true) {
    return;
  }
  loading.value = true;
  try {

    await update(form.value);
    MessagePlugin?.success?.(`操作成功`);
    visible.value = false;
    emit?.('success');
    formRef?.value?.reset();

  } catch (t) {
  } finally {
    loading.value = false;
  }
};
const handleCancel = () => {
  visible.value = false;
};
const openDialog = async (id?: string) => {
  visible.value = true;
  if (id) {
    loading.value = true;
    form.value.id = id;

    const val = await getById(id);
    if (val && Object?.keys?.(val)?.length) {
      form.value = { ...form?.value, ...val, }
    }
    loading.value = false;
  }
};
defineExpose({
  openDialog,
});
const emit = defineEmits(['success']);
</script>
<style lang="less" scoped>
/* 可以在这里添加自定义样式 */
</style>
